{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-06-03T15:29:12.330930Z",
     "start_time": "2025-06-03T15:28:55.420878Z"
    }
   },
   "source": [
    "import skmob\n",
    "import pandas as pd\n",
    "import geopandas as gpd\n",
    "from skmob.models.epr import DensityEPR\n",
    "from skmob.models.markov_diary_generator import MarkovDiaryGenerator\n",
    "from skmob.preprocessing import filtering, compression, detection, clustering\n",
    "from skmob.models.epr import Ditras"
   ],
   "outputs": [],
   "execution_count": 1
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "#### 必要数据读取及参数",
   "id": "5e0913aa7fa52130"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-03T15:29:16.316385Z",
     "start_time": "2025-06-03T15:29:16.030114Z"
    }
   },
   "cell_type": "code",
   "source": [
    "json_path = \"./tessellation.geojson\"\n",
    "traj_path = \"./trajectory.csv\"\n",
    "df = pd.read_csv(traj_path , sep='\\t')\n",
    "tessellation = gpd.read_file(json_path)\n",
    "start_time = pd.to_datetime('2019/01/01 08:00:00')\n",
    "end_time = pd.to_datetime('2019/01/14 08:00:00')"
   ],
   "id": "8ae2c9cb91c0c985",
   "outputs": [],
   "execution_count": 2
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "### EPR",
   "id": "910808f00475b125"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-03T15:29:28.851105Z",
     "start_time": "2025-06-03T15:29:19.825474Z"
    }
   },
   "cell_type": "code",
   "source": [
    "depr = DensityEPR()\n",
    "tdf = depr.generate(start_time, end_time, tessellation, relevance_column='population', n_agents=100, show_progress=True)\n",
    "\n",
    "print(tdf.parameters)"
   ],
   "id": "bc974d933f7d2502",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "  0%|          | 0/100 [00:00<?, ?it/s]D:\\Environment\\Envs\\python3.10.6\\lib\\site-packages\\skmob\\models\\gravity.py:43: RuntimeWarning: divide by zero encountered in power\n",
      "  return np.power(x, exponent)\n",
      "100%|██████████| 100/100 [00:05<00:00, 19.02it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'model': {'class': <function DensityEPR.__init__ at 0x0000028506ED4C10>, 'generate': {'start_date': Timestamp('2019-01-01 08:00:00'), 'end_date': Timestamp('2019-01-14 08:00:00'), 'gravity_singly': {}, 'n_agents': 100, 'relevance_column': 'population', 'random_state': None, 'show_progress': True}}}\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-03T15:29:31.541170Z",
     "start_time": "2025-06-03T15:29:31.528653Z"
    }
   },
   "cell_type": "code",
   "source": "print(tdf)",
   "id": "799ba93dfe9ac932",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "       uid                   datetime        lat         lng\n",
      "0        1 2019-01-01 08:00:00.000000  35.629068  139.775826\n",
      "1        1 2019-01-01 08:26:40.154568  35.622325  139.769969\n",
      "2        1 2019-01-01 09:10:40.915558  35.629068  139.775826\n",
      "3        1 2019-01-01 09:54:55.430908  35.622325  139.769969\n",
      "4        1 2019-01-01 11:26:54.136825  35.629068  139.775826\n",
      "...    ...                        ...        ...         ...\n",
      "20775  100 2019-01-14 03:08:58.385884  27.166358  142.190826\n",
      "20776  100 2019-01-14 04:22:08.369858  27.680846  142.138953\n",
      "20777  100 2019-01-14 04:47:35.950521  27.122303  142.209721\n",
      "20778  100 2019-01-14 05:17:23.734730  27.496395  142.210199\n",
      "20779  100 2019-01-14 05:46:52.059119  27.680846  142.138953\n",
      "\n",
      "[20780 rows x 4 columns]\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "39605c5874211d82"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-03T15:29:39.513543Z",
     "start_time": "2025-06-03T15:29:37.335186Z"
    }
   },
   "cell_type": "code",
   "source": [
    "tdf = skmob.TrajDataFrame(df, latitude='lat', longitude='lon', user_id='user', datetime='datetime')\n",
    "ctdf = compression.compress(tdf)\n",
    "stdf = detection.stay_locations(ctdf)\n",
    "cstdf = clustering.cluster(stdf)\n",
    "\n",
    "mdg = MarkovDiaryGenerator()\n",
    "mdg.fit(cstdf, 2, lid='cluster')\n",
    "\n",
    "# set start time, end time and tessellation for the simulation\n",
    "start_time = pd.to_datetime('2019/01/01 08:00:00')\n",
    "end_time = pd.to_datetime('2019/01/14 08:00:00')\n",
    "\n",
    "# instantiate the model\n",
    "ditras = Ditras(mdg)\n",
    "\n",
    "# run the model\n",
    "ditras_tdf = ditras.generate(start_time, end_time, tessellation, relevance_column='population',\n",
    "                n_agents=3, od_matrix=None, show_progress=True)\n",
    "print(ditras_tdf.head())"
   ],
   "id": "ccc65658e5aa31b4",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "  0%|          | 0/2 [00:00<?, ?it/s]D:\\Environment\\Envs\\python3.10.6\\lib\\site-packages\\skmob\\models\\markov_diary_generator.py:198: FutureWarning: Series.fillna with 'method' is deprecated and will raise in a future version. Use obj.ffill() or obj.bfill() instead.\n",
      "  time_series.fillna(method='ffill', inplace=True)\n",
      "D:\\Environment\\Envs\\python3.10.6\\lib\\site-packages\\skmob\\models\\markov_diary_generator.py:199: FutureWarning: Series.fillna with 'method' is deprecated and will raise in a future version. Use obj.ffill() or obj.bfill() instead.\n",
      "  time_series.fillna(method='bfill', inplace=True)\n",
      "D:\\Environment\\Envs\\python3.10.6\\lib\\site-packages\\skmob\\models\\markov_diary_generator.py:226: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`\n",
      "  loc_h = time_series[slot]  # loc_h  ,   abstract location at the current slot\n",
      "D:\\Environment\\Envs\\python3.10.6\\lib\\site-packages\\skmob\\models\\markov_diary_generator.py:227: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`\n",
      "  next_loc_h = time_series[slot + 1]  # d_{h+1},   abstract location at the next slot\n",
      "D:\\Environment\\Envs\\python3.10.6\\lib\\site-packages\\skmob\\models\\markov_diary_generator.py:244: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`\n",
      "  loc_hh = time_series[j]\n",
      "D:\\Environment\\Envs\\python3.10.6\\lib\\site-packages\\skmob\\models\\markov_diary_generator.py:272: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`\n",
      "  loc_hh = time_series[j]\n",
      "D:\\Environment\\Envs\\python3.10.6\\lib\\site-packages\\skmob\\models\\markov_diary_generator.py:198: FutureWarning: Series.fillna with 'method' is deprecated and will raise in a future version. Use obj.ffill() or obj.bfill() instead.\n",
      "  time_series.fillna(method='ffill', inplace=True)\n",
      "D:\\Environment\\Envs\\python3.10.6\\lib\\site-packages\\skmob\\models\\markov_diary_generator.py:199: FutureWarning: Series.fillna with 'method' is deprecated and will raise in a future version. Use obj.ffill() or obj.bfill() instead.\n",
      "  time_series.fillna(method='bfill', inplace=True)\n",
      "D:\\Environment\\Envs\\python3.10.6\\lib\\site-packages\\skmob\\models\\markov_diary_generator.py:226: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`\n",
      "  loc_h = time_series[slot]  # loc_h  ,   abstract location at the current slot\n",
      "D:\\Environment\\Envs\\python3.10.6\\lib\\site-packages\\skmob\\models\\markov_diary_generator.py:227: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`\n",
      "  next_loc_h = time_series[slot + 1]  # d_{h+1},   abstract location at the next slot\n",
      "100%|██████████| 2/2 [00:00<00:00, 39.11it/s]\n",
      "  0%|          | 0/3 [00:00<?, ?it/s]D:\\Environment\\Envs\\python3.10.6\\lib\\site-packages\\skmob\\models\\gravity.py:43: RuntimeWarning: divide by zero encountered in power\n",
      "  return np.power(x, exponent)\n",
      "D:\\Environment\\Envs\\python3.10.6\\lib\\site-packages\\skmob\\models\\gravity.py:43: RuntimeWarning: divide by zero encountered in power\n",
      "  return np.power(x, exponent)\n",
      " 67%|██████▋   | 2/3 [00:00<00:00, 17.28it/s]D:\\Environment\\Envs\\python3.10.6\\lib\\site-packages\\skmob\\models\\gravity.py:43: RuntimeWarning: divide by zero encountered in power\n",
      "  return np.power(x, exponent)\n",
      "100%|██████████| 3/3 [00:00<00:00, 15.81it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   uid            datetime        lat         lng\n",
      "0    1 2019-01-01 08:00:00  33.106377  139.797865\n",
      "1    1 2019-01-01 17:00:00  33.125902  139.688078\n",
      "2    1 2019-01-01 22:00:00  33.106377  139.797865\n",
      "3    1 2019-01-01 23:00:00  33.125902  139.688078\n",
      "4    1 2019-01-02 00:00:00  33.106377  139.797865\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-03T15:30:26.637024Z",
     "start_time": "2025-06-03T15:30:26.612384Z"
    }
   },
   "cell_type": "code",
   "source": "ditras_tdf.to_csv(\"./ditras_tdf.csv\", index=False)",
   "id": "61e62de828fc2f33",
   "outputs": [],
   "execution_count": 6
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "#### SpatialEPR",
   "id": "52127dc7ae053b42"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-03T15:30:38.823571Z",
     "start_time": "2025-06-03T15:30:29.833085Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from skmob.models.epr import SpatialEPR\n",
    "sepr = SpatialEPR()\n",
    "tdf = sepr.generate(start_time, end_time, tessellation, n_agents=100, show_progress=True)\n",
    "print(tdf.head())"
   ],
   "id": "8605689ee2f8672a",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "  0%|          | 0/100 [00:00<?, ?it/s]D:\\Environment\\Envs\\python3.10.6\\lib\\site-packages\\skmob\\models\\gravity.py:43: RuntimeWarning: divide by zero encountered in power\n",
      "  return np.power(x, exponent)\n",
      "100%|██████████| 100/100 [00:05<00:00, 19.46it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   uid                   datetime        lat         lng\n",
      "0    1 2019-01-01 08:00:00.000000  35.622977  139.663385\n",
      "1    1 2019-01-01 10:42:00.702162  35.777734  139.806327\n",
      "2    1 2019-01-01 11:16:17.557735  35.749474  139.860956\n",
      "3    1 2019-01-01 12:01:12.572160  35.777734  139.806327\n",
      "4    1 2019-01-01 14:35:04.038514  35.749474  139.860956\n"
     ]
    }
   ],
   "execution_count": 7
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-03T15:30:59.505395Z",
     "start_time": "2025-06-03T15:30:59.347022Z"
    }
   },
   "cell_type": "code",
   "source": "tdf.to_csv(\"./tdf.csv\", index=False)",
   "id": "98f6854ca5172f5",
   "outputs": [],
   "execution_count": 9
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "#### Markov Diary Generator",
   "id": "2a5b3ddc480c4c4"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-03T15:30:40.693909Z",
     "start_time": "2025-06-03T15:30:38.954715Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from skmob.models.markov_diary_generator import MarkovDiaryGenerator\n",
    "from skmob.preprocessing import filtering, compression, detection, clustering\n",
    "\n",
    "tdf = skmob.TrajDataFrame(df, latitude='lat', longitude='lon', user_id='user', datetime='datetime')\n",
    "\n",
    "ctdf = compression.compress(tdf)\n",
    "stdf = detection.stops(ctdf)\n",
    "cstdf = clustering.cluster(stdf)\n",
    "\n",
    "mdg = MarkovDiaryGenerator()\n",
    "mdg.fit(cstdf, 2, lid='cluster')\n",
    "\n",
    "diary = mdg.generate(100, start_time)\n",
    "print(diary)"
   ],
   "id": "89c60328b582a76",
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "module 'skmob.preprocessing.detection' has no attribute 'stops'",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mAttributeError\u001B[0m                            Traceback (most recent call last)",
      "Cell \u001B[1;32mIn[8], line 7\u001B[0m\n\u001B[0;32m      4\u001B[0m tdf \u001B[38;5;241m=\u001B[39m skmob\u001B[38;5;241m.\u001B[39mTrajDataFrame(df, latitude\u001B[38;5;241m=\u001B[39m\u001B[38;5;124m'\u001B[39m\u001B[38;5;124mlat\u001B[39m\u001B[38;5;124m'\u001B[39m, longitude\u001B[38;5;241m=\u001B[39m\u001B[38;5;124m'\u001B[39m\u001B[38;5;124mlon\u001B[39m\u001B[38;5;124m'\u001B[39m, user_id\u001B[38;5;241m=\u001B[39m\u001B[38;5;124m'\u001B[39m\u001B[38;5;124muser\u001B[39m\u001B[38;5;124m'\u001B[39m, datetime\u001B[38;5;241m=\u001B[39m\u001B[38;5;124m'\u001B[39m\u001B[38;5;124mdatetime\u001B[39m\u001B[38;5;124m'\u001B[39m)\n\u001B[0;32m      6\u001B[0m ctdf \u001B[38;5;241m=\u001B[39m compression\u001B[38;5;241m.\u001B[39mcompress(tdf)\n\u001B[1;32m----> 7\u001B[0m stdf \u001B[38;5;241m=\u001B[39m \u001B[43mdetection\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mstops\u001B[49m(ctdf)\n\u001B[0;32m      8\u001B[0m cstdf \u001B[38;5;241m=\u001B[39m clustering\u001B[38;5;241m.\u001B[39mcluster(stdf)\n\u001B[0;32m     10\u001B[0m mdg \u001B[38;5;241m=\u001B[39m MarkovDiaryGenerator()\n",
      "\u001B[1;31mAttributeError\u001B[0m: module 'skmob.preprocessing.detection' has no attribute 'stops'"
     ]
    }
   ],
   "execution_count": 8
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "18ddde67b07bace2"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "### Gravity",
   "id": "6590e30ce1bcb1fc"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
